package com.example.rabbitdemo.exchanger.headers;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.HeadersExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

// 1. 配置类
@Configuration
public class HeadersExchangeConfig {
    
    @Bean
    public HeadersExchange headersExchange() {
        return new HeadersExchange("exchange.headers");
    }
    
    @Bean
    public Queue jsonQueue() {
        return new Queue("queue.json");
    }
    
    @Bean
    public Queue xmlQueue() {
        return new Queue("queue.xml");
    }
    
    // 绑定规则：要求消息头必须包含 "format=json" 且 "type=report"
    @Bean
    public Binding jsonBinding(HeadersExchange headersExchange, Queue jsonQueue) {
        Map<String, Object> map = new HashMap<>();
        map.put("format", "json");
        map.put("type", "report");
        // x-match 设置为 "all" 表示必须匹配所有键值对
        return BindingBuilder.bind(jsonQueue).to(headersExchange).whereAll(map).match();
    }
    
    // 绑定规则：要求消息头包含 "format=xml" 或 "priority=high"
    @Bean
    public Binding xmlBinding(HeadersExchange headersExchange, Queue xmlQueue) {
        Map<String, Object> map = new HashMap<>();
        map.put("format", "xml");
        map.put("priority", "high");
        // x-match 设置为 "any" 表示匹配任意一个键值对即可
        return BindingBuilder.bind(xmlQueue).to(headersExchange).whereAny(map).match();
    }
}